package com.example.demo.service;

import com.example.demo.entity.Account;
import com.example.demo.entity.Customer;
import com.example.demo.repository.AccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AccountService implements BaseService<Account> {

    @Autowired
    AccountRepository accountRepository;

    @Autowired
    CustomerService customerService;


    @Override
    public Account findByID(int id) {
        return accountRepository.findById(id).get();
    }

    @Override
    public List<Account> findAll() {
        return accountRepository.findAll();
    }

    @Override
    public Account save(Account account) {
        if (account.getCustomer().getCustomerId() != null) {
            Customer byID = customerService.findByID(account.getCustomer().getCustomerId());
            account.setCustomer(byID);
        }
        return accountRepository.save(account);
    }

    @Override
    public boolean deleteByid(int id) {
        accountRepository.deleteById(id);
        boolean present = accountRepository.findById(id).isPresent();
        return !present;
    }

    @Override
    public Account updateById(Account account) {
        Account account1 = accountRepository.findById(account.getAccountNumber()).get();
        if (account.getBalance()!=0) {
            account1.setBalance(account.getBalance());
        }
        if (account.getAccountName()!=null) {
            account1.setAccountName(account.getAccountName());
        }
        if (account.getCustomer().getCustomerId()!=null) {
            Customer byID1 = customerService.findByID(account.getCustomer().getCustomerId());
            account1.setCustomer(byID1);
        }
        Account save = accountRepository.save(account1);
        return save;
    }

    @Override
    public Page<Account> findAllByPage(int pageNum) {
        PageRequest of = PageRequest.of(pageNum, 5);
        Page<Account> all = accountRepository.findAll(of);
        return all;
    }

    public List<Account> findAllByCustomer_CustomerId(int id){
        List<Account> allByCustomer_customerId = accountRepository.findAllByCustomer_CustomerId(id);
        return allByCustomer_customerId;
    }


}
